<template>
  <div ref="editorContainer" id="editorContainer"></div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { EditorView, basicSetup } from "codemirror"
import { cpp } from '@codemirror/lang-cpp';
import { oneDark } from '@codemirror/theme-one-dark';
import * as autocomplete from '@codemirror/autocomplete';

const { autocompletion } = autocomplete;
const cppKeywords = [
  "auto", "break", "case", "char", "const", "continue", "default",
  "do", "double", "else", "enum", "extern", "float", "for", "goto",
  "if", "int", "long", "register", "return", "short", "signed",
  "sizeof", "static", "struct", "switch", "typedef", "union",
  "unsigned", "void", "volatile", "while", "vec2", "vec3", "vec4", "void", "main", "uniform", "cin", "cout", "uv"
];
function cppCompletion(context) {
  let word = context.matchBefore(/\w*/);
  if (word.from == word.to && !context.explicit) return null;
  return {
    from: word.from,
    options: cppKeywords.map(keyword => ({ label: keyword, type: "keyword" }))
  };
}
const editorContainer = ref(null);
const code = ref('console.log("Hello, World!");');
onMounted(() => {
  let view = new EditorView({
    extensions: [
      basicSetup,
      cpp(),
      oneDark,
      autocompletion({ override: [cppCompletion] }) // 添加自动补全
    ],
    parent: editorContainer.value
  });
  console.log('view ---->', view);
  // 当编辑器内容改变时，更新code变量
  if (view.state.field(EditorView.updateListener)) {
    view.state.field(EditorView.updateListener, (update) => {
      if (update.docChanged) {
        code.value = view.state.doc.toString();
      }
    });
  }
});
</script>
<style>
/* @import "codemirror/lib/codemirror.css"; */
#editorContainer {
  height: 100vh;
  text-align: left;
}

#editorContainer .cm-editor {
  height: 100%;
}

</style>